﻿using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using X23.Application.HttpManagement.WeChatDto;

namespace X23.Application.HttpManagement
{
    public class WeChatHttpService : IWeChatHttpService
    {
        private const string WeChat = nameof(WeChat);
        private const string APPID = "wx0f150089970d8555";
        private const string APPSECRET = "c90128d945c2b224a37fa821d98d976e";

        private readonly Dictionary<string, string> headers = new();
        private readonly IHttpClientFactory _httpClientFactory;
        public WeChatHttpService(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<JsCodeResDto> JsCode2Session(string code)
        {
            //https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
            //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code 
            return await GetAsync<JsCodeResDto>($"https://api.weixin.qq.com/sns/jscode2session?appid={APPID}&secret={APPSECRET}&js_code={code}&grant_type=authorization_code");
        }

        private async Task<T> GetAsync<T>(string url)
        {
            var client = _httpClientFactory.CreateClient(WeChat);
            var request = new HttpRequestMessage(HttpMethod.Get, url);
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }
            var response = await client.SendAsync(request);
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<T>(result);
            }
            else
            {
                throw new Exception($"HttpCode:{response.StatusCode}，Message:{response.ReasonPhrase}");
            }
        }

        private async Task<T> PostAsync<TReq, T>(string url, TReq req)
        {
            var client = _httpClientFactory.CreateClient(WeChat);
            var requestContent = new StringContent(JsonConvert.SerializeObject(req), Encoding.UTF8, "application/json");
            if (headers != null)
            {
                foreach (var head in headers)
                {
                    requestContent.Headers.Add(head.Key, head.Value);
                }
            }

            var response = await client.PostAsync(url, requestContent);
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<T>(result);
            }
            else
            {
                throw new Exception($"HttpCode:{response.StatusCode}，Message:{response.ReasonPhrase}");
            }
        }
    }
}
